package com.java01.net.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class TimeServer {

	private final String SERVER_ADDRESS = "localhost"; 
	private final int port = 1688;
	private boolean listening=true;
	private InetSocketAddress socket;
	private ServerSocket serverSocket;
	
	public TimeServer(){
	
		try {
			socket = new InetSocketAddress(InetAddress.getByName(SERVER_ADDRESS),port);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return;
		}
		
		try {
			serverSocket = new ServerSocket();
			serverSocket.bind(socket);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		
		new Thread(){
			@Override
			public void run() {
				while (listening){
					Socket serviceSocket = null;
					PrintWriter out = null;
					try {
						serviceSocket=serverSocket.accept();
						out = new PrintWriter(serviceSocket.getOutputStream(), true);
						out.print(System.currentTimeMillis());
					}catch (IOException e) {
						System.err.println(e.getMessage());
					}finally{
						if(out!=null){
							out.close();
						}

						if(serviceSocket!=null){
							try {
								serviceSocket.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}.start();
	}
	
	public static void main(String[] args) {
		new TimeServer();
	}
}
